<?php

namespace App\Http\Controllers\Admin;

use App\Model\Facades\AdminMenus;
use App\Model\Facades\AdminPermissions;
use App\Model\Facades\AdminRoles;
use Illuminate\Support\Facades\Session;


class RolesCtrl extends CommonCtrl
{
    //
    public function index()
    {
        $data['query'] = AdminRoles::create()->index();
        return $this->responseView('index', $data);
    }

    public function create()
    {
        return $this->responseView('create');
    }

    public function store()
    {
        list($error, $info) = AdminRoles::create()->add();

        if (is_object($info))
            return back()->withErrors($info)->withInput();

        return $error ? $this->success('添加成功') : $this->error('添加失败');
    }

    public function edit($id)
    {
        $data['info'] = AdminRoles::create()->show($id);
        return $this->responseView('edit', $data);
    }

    public function renovate($id)
    {
        $data['info'] = AdminRoles::create()->show($id);

        list($error, $info) = AdminRoles::create()->edit($id);
        if (is_object($info))
            return back()->withErrors($info)->withInput();

        return $error ? $this->success('添加成功') : $this->error('添加失败');
    }

    /**添加用户权限
     * @param $id
     */
    public function permussion($id)
    {
        $data['info'] = AdminRoles::create()->show($id);
        #$data['infopms'] = array_keys($data['info']->getPermissions->keyBy('id')->toArray());
        $data['infopms'] = $data['info']->getPermissions->pluck('id')->toArray();

        $data['permussion'] = AdminPermissions::create()->index();
        return $this->responseView('permussion', $data);
    }

    public function setpmsion($id)
    {
        $result = AdminRoles::create()->sys($id);
        return $result ? $this->success('操作成功') : $this->error('操作失败');
    }

    public function addmuen($id)
    {
        if (in_array($id, [1, 2])) {
            request()->session()->flash('info', '管理员和自定义角色不需要编辑');
            return back();
        }

        $data['info'] = AdminRoles::create()->show($id);
        $info_pms = $data['info']->getPermissions->pluck('id')->toArray();
        $data['muen'] = AdminMenus::create()->getToTreeHtml($info_pms);
        return $this->responseView('addmuen', $data);
    }

    public function setAddMuen($id)
    {
        $query = AdminRoles::create()->menuSys($id);
        return $query ? $this->success('操作成功') : $this->error('操作失败');
    }

}
